import { SoqlBuilder } from '../../salesforce/queryBuilder';
import { AnswersQuestions, Question, UsesAbilities } from '@serenity-js/core';

import { ExistingRecord, Record, recordToString } from '../../salesforce/models/record';
import { UseSystem } from '../abilities';

export class ActualSalesforceRecord extends Question<ExistingRecord> {
  public static like(record: Record) {
    return new this(record);
  }

  private constructor(private readonly recordShape: Record) {
    super(recordToString(recordShape));
  }

  async answeredBy(actor: AnswersQuestions & UsesAbilities): Promise<ExistingRecord> {
    const useSystemAbility: UseSystem = actor.abilityTo(UseSystem);
    const api = await useSystemAbility.salesforceApi();
    const records = await api.query(SoqlBuilder.fromRecord(this.recordShape).limit(1));
    if (records.length) {
      return records[0];
    }
    return null;
  }
}
